<template>
  <div class="table-page lf">
    <GiTable
      row-key="id"
      id="corporateInvoice"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
      :simple="true"
    >
      <template #custom-extra>
        <a-form :model="listParams" layout="inline" size="small" class="w-full flex flex-wrap">
          <a-form-item label="提现账号类型" class="w-36n">
            <a-select class="w-36n" v-model="listParams.type" allow-clear placeholder="请选择" @change="changeCurrent(1)">
              <a-option value="" label="全部"></a-option>
              <a-option :value="1" label="法人支付宝"></a-option>
              <a-option :value="2" label="法人银行卡"></a-option>
              <a-option :value="3" label="企业对公户"></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="邀请码" class="w-34n">
            <a-input
              v-model="listParams.inviteCode"
              placeholder="请输入"
              @pressEnter="changeCurrent(1)"
            >
            </a-input>
          </a-form-item>
          <a-form-item label="手机号" class="w-34n">
            <a-input
              v-model="listParams.mobile"
              placeholder="请输入"
              @pressEnter="changeCurrent(1)"
            >
            </a-input>
          </a-form-item>
          <a-form-item label="发票提交月份">
            <a-month-picker v-model="listParams.month" @change="changeCurrent(1)" />
          </a-form-item>
          <a-form-item label="发票状态" class="w-36n">
            <a-select class="w-36n" allow-clear v-model="listParams.status" placeholder="请选择" @change="changeCurrent(1)">
              <a-option value="" label="全部"></a-option>
              <a-option :value="0" label="待提交发票"></a-option>
              <a-option :value="10" label="待审核"></a-option>
              <a-option :value="20" label="审核通过"></a-option>
              <a-option :value="30" label="审核不通过"></a-option>
              <a-option :value="40" label="已退回余额"></a-option>
            </a-select>
          </a-form-item>
          <a-form-item hide-label class="w-fit">
            <a-button type="primary" size="small" @click="changeCurrent(1)">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button class="ml-m" size="small" @click="onResetSearch">
              <template #icon>
                <icon-sync />
              </template>
              <template #default>重置</template>
            </a-button>
          </a-form-item>
        </a-form>
      </template>
      <template #user="{ record }">
        <div class="flex-col">
          <span>邀请码：{{ record.user.inviteCode }}</span>
          <span>手机号：{{ record.user.mobile }}</span>
        </div>
      </template>
      <template #account="{ record }">
        <div class="flex-col" v-if="record?.accountInfo.type == 1">
          <span>法人：{{ record?.accountInfo?.accountName ?? '--' }}</span>
          <span>支付宝：{{ record?.accountInfo?.accountNumber ?? '--' }}</span>
        </div>
        <div class="flex-col" v-else-if="record?.accountInfo.type == 2">
          <span>法人：{{ record?.accountInfo?.accountName ?? '--' }}</span>
          <span>银行卡：{{ record?.accountInfo?.bankName ?? '--' }}<br/> {{ record?.accountInfo?.accountNumber ?? '--' }}</span>
        </div>
        <div class="flex-col" v-else-if="record?.accountInfo.type == 3">
          <span>户名：{{ record?.accountInfo.accountName ?? '--' }}</span>
          <span>对公账户：{{ record?.accountInfo?.accountNumber ?? '--' }} </span>
          <span>开户行：{{ record?.accountInfo?.bankName ?? '--' }} </span>
        </div>
        <div v-else>--</div>
      </template>
      <template #enterpriseInfo="{ record }">
        <div class="flex flex-a-c">
          <a-image :src="record.enterpriseInfo.licenseImg" :width="60"></a-image>
          <a-popover title="企业认证信息" position="right">
            <a-button type="text" class="ml-14">详情</a-button>
            <template #content>
              <div class="flex-col">
                <div class="flex-col mt-4">
                  <div class="flex">
                    <span class="text-size-12 font-bold">营业执照：</span>
                    <a-image class="ml-20" :src="record.enterpriseInfo.licenseImg" :width="100"></a-image>
                  </div>
                  <div class="flex">
                    <span class="text-size-12 font-bold">公司名称：</span>
                    <span class="text-size-12 font-bold">{{ record.enterpriseInfo.businessName }}</span>
                  </div>
                  <div class="flex">
                    <span class="text-size-12 font-bold">执照号码：</span>
                    <span class="text-size-12 font-bold">{{ record.enterpriseInfo.licenseNo }}</span>
                  </div>
                  <div class="flex">
                    <span class="text-size-12 font-bold">法人姓名：</span>
                    <span class="text-size-12 font-bold">{{ record.enterpriseInfo.legalPerson }}</span>
                  </div>
                  <div class="flex">
                    <span class="text-size-12 font-bold">地址信息：</span>
                    <span class="text-size-12 font-bold">{{ record.enterpriseInfo.address }}</span>
                  </div>
                </div>
              </div>
            </template>
          </a-popover>
        </div>
      </template>
      <template #invoice="{ record }">
        <div class="flex flex-a-c" v-if="record.fInfo">
          <img src="/src/assets/images/ofd.png" v-if="record.fInfo.url.toLowerCase().includes('ofd')" style="width: 18px;height: 18px;display: inline-block;"></img>
          <img src="/src/assets/images/pdf.png" v-else style="width: 18px;height: 18px;display: inline-block;"></img>
          <span class="ml-10">{{ record.fInfo.name }}<span class="text-theme cursor-pointer ml-10" @click="onDown(record)">下载</span><span class="text-theme cursor-pointer ml-10" @click="onPre(record)">预览</span></span>
        </div>
        <div class="flex flex-j-c" v-else>--</div>
      </template>
      <template #invoiceTime="{ record }">
        <div class="flex-col">
          <span>提交：{{ record?.createdAt ?? '-' }}</span>
          <span
            >审核：{{
              record?.status == 10
                ? `待审核${record.commitTimes > 1 ? '（第' + record.commitTimes + '次 ）' : ''}`
                :  `${record?.auditTime ?? '-'}${record.commitTimes > 1 ? '(（第' + record.commitTimes + '次 ）' : ''}` 
            }}</span
          >
        </div>
      </template>
      <template #amount="{ record }">
        <span class="font-bold">￥{{record.amount}}</span>
      </template>
      <template #status="{ record }">
        <div class="flex flex-j-c">
          <GiDot
            :type="
              record.status == 0
                ? 'warning'
                : record.status == 10
                ? 'danger'
                : record.status == 20
                ? 'success'
                : record.status == 30
                ? 'info'
                : record.status == 40
                ? 'info'
                : 'info'
            "
            :text="
              record.status == 0
                ? '待提交发票'
                : record.status == 10
                ? '待审核'
                : record.status == 20
                ? '审核通过'
                : record.status == 30
                ? '审核不通过'
                : record.status == 40
                ? '已退回余额'
                : '--'
            "
            :animation="false"
          />
        </div>
      </template>
      <template #action="{ record }">
        <a-button type="primary" size="small" shape="round" @click="onExamine(record)" :disabled="record.status != 0 && record.status != 10"> 审核 </a-button>
      </template>
      <template #refuseReason="{ record }">
        <div v-if="record.refuseReason" class="text-red text-overflow-2">
          <a-tooltip :content="record.refuseReason">
            <span>{{ record.refuseReason }}</span>
          </a-tooltip>
        </div>
        <span v-else>--</span>
      </template>
    </GiTable>


    <!-- <embed src="document.pdf" type="application/pdf" width="100%" height="600px" /> -->
  </div>
</template>

<script setup>
import { usePagination, useLayer } from '@/hooks'
import { transferInvoiceList, lgUserDelete } from '@/apis'
import { deepClone, deleteEmpty } from '@/utils/common'
import Examine from './Examine.vue'
import dayjs from 'dayjs'
import download from 'downloadjs'
defineOptions({ name: 'corporateInvoice' })

const columns = ref([
  {
    title: '提现用户',
    slotName: 'user',
    width: 160
  },
  {
    title: '提现金额',
    dataIndex: 'amount',
    align:'center',
    slotName: 'amount',
    width: 120
  },
  {
    title: '提现账号',
    slotName: 'account',
    width: 220
  },
  {
    title: '企业认证信息',
    slotName: 'enterpriseInfo',
    width: 200
  },
  {
    title: '发票',
    align: 'center',
    slotName: 'invoice',
    width:220
  },
  {
    title: '发票时间',
    slotName: 'invoiceTime',
    width: 260
  },
  {
    title: '状态',
    slotName: 'status',
    align: 'center',
    width: 120
  },
  {
    title: '操作',
    width: 120,
    align: 'center',
    slotName: 'action'
  },
  {
    title: '备注',
    slotName: 'refuseReason',
    width: 120
  }
])

const loading = ref(false)
const tableData = ref([])
const total = ref(0)

const listParams = reactive({
  page: 1,
  size: 10,
  inviteCode:undefined,
  type: undefined,
  status: undefined,
  month: dayjs().format('YYYY-MM'),
  mobile:undefined
})

const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: listParams.size })

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.size = pagination.pageSize
    const param = deepClone(listParams)
    const res = await transferInvoiceList(deleteEmpty(param))
    tableData.value = res.data.data.map(item=>{
      return {
        ...item,
        fInfo:item.invoiceFileUrl?getFileName(item.invoiceFileUrl):null
      }
    })
    total.value = res?.data?.total || 0
    console.log(tableData.value)
    setTotal(total.value)
  } finally {
    loading.value = false
  }
}

// 获取文件名
const getFileName = (url)=> {
    // 使用正则匹配文件名部分
    const match = url.match(/([^/]+\.[^/]+)$/);
    return {
      name:match ? match[0] : null,
      url:url,
      formatUrl:encodeURIComponent(url)
    }
}

onMounted(() => {
  getTableData()
})

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

// 重置筛选查询
const onResetSearch = () => {
  listParams.type = listParams.status = listParams.month = listParams.inviteCode = listParams.mobile = undefined
  changeCurrent(1)
}

// 添加/编辑
const onExamine = (item) => {
  useLayer().openLayer(
    Examine,
    {
      title: `发票审核${item.status==0?'（退回余额）':''}`,
      params:{...item},
      area: ['1000px', '80%']
    },
    getTableData
  )
}

const getFileType = (extension)=> {
  const imageExtensions = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
  const txtExtensions = ['txt'];
  const excelExtensions = ['xls', 'xlsx'];
  const wordExtensions = ['doc', 'docx'];
  const pdfExtensions = ['pdf'];
  const pptExtensions = ['ppt', 'pptx'];
  const videoExtensions = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
  const radioExtensions = ['mp3', 'wav', 'wmv'];

  if (imageExtensions.includes(extension)) return 'image';
  if (txtExtensions.includes(extension)) return 'txt';
  if (excelExtensions.includes(extension)) return 'excel';
  if (wordExtensions.includes(extension)) return 'word';
  if (pdfExtensions.includes(extension)) return 'pdf';
  if (pptExtensions.includes(extension)) return 'ppt';
  if (videoExtensions.includes(extension)) return 'video';
  if (radioExtensions.includes(extension)) return 'radio';

  return 'other';
}

// 下载
const onDown = async(record)=>{
  const url = record.fInfo.url
  const strFileName = record.fInfo.name
  const type = strFileName.split('.')[1]
  const strMimeType =  getFileType(type)
  let xmlHttp = null;
  if (window.ActiveXObject) {
      // IE6, IE5 浏览器执行代码
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } else if (window.XMLHttpRequest) {
      // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
      xmlHttp = new XMLHttpRequest();
  }
  //2.如果实例化成功，就调用open（）方法：
  if (xmlHttp != null) {
      xmlHttp.open("get", url, true);
      xmlHttp.responseType = 'blob';//关键
      xmlHttp.send();
      xmlHttp.onreadystatechange = doResult; //设置回调函数
}
  function doResult() {
    if (xmlHttp.readyState == 4) { //4表示执行完成
        if (xmlHttp.status == 200) { //200表示执行成功
            download(xmlHttp.response, strFileName, strMimeType);
        }
      }
  }
}

// 预览
const onPre = (record)=>{
  window.open(record.fInfo.url)
}
</script>

<style lang="scss" scoped>

</style>
